#include <iostream>
#include <string>
#include <ctime>
#include <cassert>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"

static void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]); //获取IP和端口

    Sock sockfd;
    sockfd.Socket();
    if (!sockfd.Connect(serverip, serverport))
        return 1;

    srand(time(nullptr) ^ getpid()); // 种随机数种子
    int cnt = 1;
    const std::string opers = "+-*/%-=&^";

    std::string inbuffer_stream;
    while (cnt <= 5)
    {
        std::cout << "===============第" << cnt << "次测试....., " << "===============" << std::endl;
        int x = rand() % 100 + 1;
        usleep(1234);
        int y = rand() % 100;
        usleep(4321);
        char oper = opers[rand() % opers.size()];
        Request req(x, y, oper);
        req.DebugPrint();

        // 下面是根据协议发送给对方
        std::string package;
        req.Serialize(&package);                    // 序列化
        package = Encode(package);                  // 形成报文
        int fd = sockfd.Fd();                       // 获取套接字
        write(fd, package.c_str(), package.size()); // 将请求从客户端往服务端写过去

        // 下面是读取服务器发来的结果并解析
        char buffer[128];
        ssize_t n = read(sockfd.Fd(), buffer, sizeof(buffer)); // 读取服务器发回来的结果，但是这里也无法保证能读取到一个完整的报文
        if (n > 0)                                             // 读成功了
        {
            buffer[n] = 0;
            inbuffer_stream += buffer; // "len"\n"result code"\n
            std::cout << inbuffer_stream << std::endl;
            std::string content;
            bool r = Decode(inbuffer_stream, &content); // 去掉报头"result code"\n
            assert(r);                                  // r为真说明报头成功去掉
            Response resp;
            r = resp.DeSerialize(content); // 对有效荷载进行反序列化
            assert(r);

            resp.DebugPrint(); // 打印结果
        }
        std::cout << "=================================================" << std::endl;
        sleep(1);
        cnt++;
    }

    sockfd.Close();
    return 0;
}